package com.mediacloud.app.newsmodule.activity

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.location.BDLocation
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.newsmodule.R
import kotlinx.android.synthetic.main.activity_media_list.*
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.model.interfaces.ILocation
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil.getLocation
import com.mediacloud.app.model.interfaces.PermissionUtil.invokeLocationPermission
import com.mediacloud.app.model.interfaces.PermissionUtil.isGpsEnabled
import com.mediacloud.app.model.interfaces.PermissionUtil.showGPSPop
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.model.MediaListBean
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


/**
 * 强军号榜单列表
 */
class MediaListActivity : BaseBackActivity(), OnRefreshLoadMoreListener {
    var mediaListAdapter: MediaListAdapter? = null
    var pageNum = 1
    var listType: String = "1"
    var type: String = "1"
    override fun getLayoutResID(): Int {
        return R.layout.activity_media_list
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val title = intent.getStringExtra("title")
        val headImg = intent.getStringExtra("head_img")
        val typeOriginal = intent.getStringExtra("list_type")//1昨日榜，2周榜，3月榜,4本地榜

        typeOriginal?.let {
            listType = it
        }

        when (listType) {
            "1" -> {
                type = "1"
            }
            "2" -> {
                type = "3"
            }
            "3" -> {
                type = "4"
            }
            "5" -> {
                type = "5"
            }
            "6" -> {
                type = "6"
            }
        }
        setTitle(title)
        mTitileBar.setBackgroundColor(Color.WHITE)

        if (TextUtils.isEmpty(headImg)) {
            ivHeadImg.visibility = View.GONE
        } else {
            ivHeadImg.load(headImg)
            ivHeadImg.visibility = View.VISIBLE
        }
        rvMedialist?.layoutManager =
            LinearLayoutManager(this).apply { orientation = LinearLayoutManager.VERTICAL }
        mediaListAdapter = MediaListAdapter(R.layout.adapter_media_item)
        mediaListAdapter?.bindToRecyclerView(rvMedialist)
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        loadingImage.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                pageNum = 1
                getList()
            }
        }
        fresh.setOnRefreshLoadMoreListener(this)
        showStateView(TYPE_LOADING, false)
        getData()
        mediaListAdapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as MediaListBean
            var articleItem = ArticleItem()
            articleItem.id = item.id
            articleItem.type = item.resourceType
            NewsItemClickUtils.OpenItemNewsHandle(
                view.context,
                articleItem.type,
                articleItem,
                CatalogItem()
            )
        }
    }

    private fun getData() {
        if (listType == "4") {//获取本地榜单
            getNativeLocation()
        } else {
            getList()
        }
    }

    private fun getNativeLocation() {
        invokeLocationPermission(this, object : IPermissionsAgree {
            override fun onAgree() {
                getLocation(this@MediaListActivity, object : ILocation {
                    override fun onLocation(location: BDLocation) {
                        getListByCity(location.city)
                    }

                    override fun onFail() {
                        showStateView(TYPE_NO_CONTENT, false)
                    }
                })
            }

            override fun onRefuse() {}
            override fun hasPermissions() {
                getLocation(this@MediaListActivity, object : ILocation {
                    override fun onLocation(location: BDLocation) {
                        getListByCity(location.city)
                    }

                    override fun onFail() {
                        if (!isGpsEnabled(this@MediaListActivity)) {
                            showGPSPop(this@MediaListActivity, "定位服务未开启", "请打开GPS定位服务")
                        }
                        showStateView(TYPE_NO_CONTENT, false)
                    }
                })
            }
        })
    }

    private fun getListByCity(city: String) {
        SpiderCmsApi.getSpiderCmsApi(this)
            .getSpiderHotArticleByCity(city, pageNum, getString(R.string.tenantid))
            .enqueue(object : Callback<BaseDataListBean<MediaListBean>> {
                override fun onResponse(

                    call: Call<BaseDataListBean<MediaListBean>>,
                    response: Response<BaseDataListBean<MediaListBean>>
                ) {
                    val body = response.body()
                    if (body !=null&& body.isSuccess) {
                        if (body.data.pageRecords.size > 0) {
                            closeStateView()
                            if (pageNum == 1) {
                                mediaListAdapter?.setNewData(body.data.pageRecords)
                            } else {
                                mediaListAdapter?.addData(body.data.pageRecords)
                            }
                        } else {
                            showStateView(TYPE_NO_CONTENT, false)
                        }

                    } else {
                        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                    }

                }

                override fun onFailure(call: Call<BaseDataListBean<MediaListBean>>, t: Throwable) {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }

            })
    }

    private fun getList() {
        SpiderCmsApi.getSpiderCmsApi(this)
            .getSpiderHotArticle(type, pageNum, 10, getString(R.string.tenantid))
            .enqueue(object : Callback<BaseDataListBean<MediaListBean>> {
                override fun onResponse(
                    call: Call<BaseDataListBean<MediaListBean>>,
                    response: Response<BaseDataListBean<MediaListBean>>
                ) {
                    fresh.finishRefresh()
                    fresh.finishLoadMore()
                    val body = response.body()
                    if (body!=null&&body.isSuccess) {
                        if (body.data.pageRecords.size > 0) {
                            closeStateView()
                            if (pageNum == 1) {
                                mediaListAdapter?.setNewData(body.data.pageRecords)
                            } else {
                                mediaListAdapter?.addData(body.data.pageRecords)
                            }
                        } else {
                            if (pageNum==1){
                                showStateView(TYPE_NO_CONTENT, false)
                            }
                        }

                    } else {
                        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                    }

                }

                override fun onFailure(call: Call<BaseDataListBean<MediaListBean>>, t: Throwable) {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }

            })
    }

    override fun getContent_show_top_color(): String? {
        return "#333333"
    }


    override fun getStatusBarColor(): Int {
        return Color.WHITE
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        pageNum = 1
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        pageNum++
        getData()
    }

}